import inquirer from "inquirer";
import { Command } from "commander";
import { saveAs as saveDeptAs } from "./dept.js";
import { saveAs as saveLakeAs } from "./lake.js";
import { createProject } from "./management.js";
import { insertProject } from "./db.js";

import {
  getProjects,
  insertManyProjects,
  initDb,
  updateProject,
} from "./db.js";
import fs from "fs";
// import project_data from "./data.json" assert{type:"json"};
import dayjs from "dayjs";

const ALL_PROJECTS = getProjects();
// const ALL_PROJECTS = []

function main() {
  console.log("Welcome to PMS!");
  fs.mkdirSync("dist", { recursive: true });

  const program = new Command();
  program.name("pms").description("项目管理工具").version("1.0.0");

  program.option("-t, --tags <tags>", "标签");
  program.option("-d, --department <department>", "科室");
  program.option("-y, --year <year>", "年份");
  program.option("-c, --compact", "简化输出");
  program.option("-f, --file <file>", "新项目");


  program
    .command("project")
    .alias("p")
    .description("创建新项目")
    .action((_) => {
      const promps = [];

      promps.push({
        type: "input",
        name: "projectName",
        message: "请输入项目名称",
        validate: function (input) {
          if (!input) {
            return "输入不能为空";
          }
          return true;
        },
      });

      inquirer.prompt(promps).then(function (answers) {
        console.log("as", answers);
        const { projectName } = answers;
        createProject(projectName);
      });
    });

  program
    .command("import")
    .alias("i")
    .description("读取新项目内容")
    .action((_) => {

      const { file } = program.opts()
      console.log('f', file);

      const project = JSON.parse(fs.readFileSync(file, "utf-8"))
      insertProject(project);

    });

  program
    .command("export")
    .alias("e")
    .description("导出项目表")
    .action((_) => {
      const promps = [];

      promps.push({
        type: "list",
        name: "type",
        message: "导出数据模板",
        choices: [
          {
            name: "分科室统计表",
            value: "stat_dept",
          },
          {
            name: "三湖统计表",
            value: "stat_lake",
          },
          {
            name: "测试",
            value: "test",
          },
        ],
      });

      inquirer.prompt(promps).then(function (answers) {
        console.log("as", answers, program.opts());
        const { type } = answers;
        let condition = program.opts();

        switch (type) {
          case "stat_dept":
            let projects = getFilteredProjects(condition);
            if (condition.year) {
              projects = filterFundYear(projects, condition.year);
            }
            saveDeptAs(projects);
            break;
          case "stat_lake":
            condition = {
              tags: "三湖",
            };
            let lakeProjects = getFilteredProjects(condition);
            if (condition.year) {
              lakeProjects = filterFundYear(lakeProjects, condition.year);
            }
            saveLakeAs(lakeProjects);
            break;
          case "test":
            // addCode();
            // initDb()
            // insertManyProjects(project_data)
            break;
          default:
            break;
        }
      });
    });

  program
    .command("money")
    .alias("m")
    .description("查询下达文号")
    .action((_) => {
      const promps = [];

      promps.push({
        type: "input",
        name: "code",
        message: "请输入下达文号",
      });

      inquirer.prompt(promps).then(function (answers) {
        console.log("as", answers, program.opts());
        const { code } = answers;
        const filteredProjects = getFilteredProjects(program.opts());

        const projects = filteredProjects.filter((item) => {
          return item.funds.some((fund) => {
            return fund.doc.code === code;
          });
        });
        console.log(
          "projects",
          projects.map((item) => item.name)
        );
      });
    });

  program
    .command("reply")
    .alias("r")
    .description("查询当年批复")
    .action((_) => {
      console.log('as', program.opts());
      let condition = program.opts();

      let projects = getFilteredProjects(program.opts());
      if (condition.year) {
        projects = filterApprovalYear(projects, condition.year);
      }
      if (condition.compact) {
        console.log(
          "projects",
          projects.map((item) => item.name)
        );
      } else {
        console.log(
          "projects",
          projects
        );
      }
    });

  program.parse(process.argv);
}

main();

function filterFundYear(projects, year) {
  const filtered = projects.filter((item) => {
    return item.funds.some((fund) => {
      if (fund.doc.date === "") {
        return false;
      } else {
        return dayjs(fund.doc.date).year().toString() === year;
      }
    });
  });
  filtered.forEach((item) => {
    item.funds = item.funds.filter((fund) => {
      return dayjs(fund.doc.date).year().toString() === year;
    });
  });
  return filtered;
}

function filterApprovalYear(projects, year) {
  const filtered = projects.filter((item) => {
    if (item.approval_doc.date === "") {
      return false;
    } else {
      return dayjs(item.approval_doc.date).year().toString() === year;
    }
  });
  return filtered;
}

function getFilteredProjects(condition) {
  const filtered = ALL_PROJECTS.filter((item) => {
    if (condition.department) {
      return item.department === condition.department;
    }
    return true;
  }).filter((item) => {
    if (condition.tags) {
      return item.tags.includes(condition.tags);
    }
    return true;
  });

  return filtered;
}

// function addCode() {
//   ALL_PROJECTS.forEach((item) => {
//     item.code = "";
//     const { id, ...val } = item;
//     updateProject(id, val);
//   });
// }
